package xyz.xcvu.ma2.module;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

import java.io.*;

@Component
@MagicModule("upload")
public class HttpUpload {

    @Comment("通过InputStream上传")
    public HttpEntity byInputStream(
            @Comment("上传路径") String uploadURL,
            @Comment("文件流") InputStream is,
            @Comment("文件名称") String fileName
    ) throws IOException{

        //创建HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uploadURL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        /*绑定文件参数，传入文件流和contentType，此处也可以继续添加其他formData参数*/
        builder.addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA,fileName);

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);

        //执行提交
        HttpResponse response = null;
        response = httpClient.execute(httpPost);
        return response.getEntity();
    }

    @Comment("byte[]保存为文件")
    public static void bytesToFile(
            @Comment("byte数组") byte[] bytes,
            @Comment("文件路径") String filePath,
            @Comment("文件名") String fileName)
    {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            file = new File(filePath + fileName);
            if (!file.getParentFile().exists()){
                //文件夹不存在 生成
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos == null) {
            } else {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
